package websphinx;

import java.util.Vector;


public class MatchGetValue implements MatchAction {

	private String name = null;

	public MatchGetValue(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	@Override
	public boolean match(Matcher matcher) {
		if (matcher.getModel() != MatchModel.GETVALUE)
			return true;

		Element child = matcher.context.getCurPointer().getChild();
		Vector result = new Vector();

		if (child != null) {
			do {
				result.add(child);
			} while ((child = child.getSibling()) != null);
		}

		if (matcher.repeatTimes.size() != 0) {
			int repeatTimes = (Integer) matcher.repeatTimes
					.get(matcher.repeatTimes.size() - 1);
			String nameX = name + Integer.toString(repeatTimes);
			matcher.data.put(nameX, result);
		} else {
			matcher.data.put(name, result);
		}

		Element father = matcher.context.getCurPointer();
		if (father.getSibling() == null)
			matcher.next = father.getParent();
		else
			matcher.next = father.getSibling();

		return true;

	}

	@Override
	public boolean apply(Matcher matcher) {
		Vector value = null;
		if (matcher.repeats.size() == 0) {
			value = (Vector) matcher.data.get(name);
		} else { // in repeat, use nameX
			int repeatTimes = (Integer) matcher.repeatTimes
					.get(matcher.repeatTimes.size() - 1);
			value = (Vector) matcher.data.get(name
					+ Integer.toString(repeatTimes));
		}

		if (value != null) {
			for (int i = 0; i < value.size(); i++) {
				matcher.applyResult.append(value.elementAt(i).toString());
			}
			return true;
		} else
			return false;
	}

}
